package com.whsxt.controller;

import com.whsxt.domain.SysMenu;
import com.whsxt.service.SysMenuService;
import com.whsxt.vo.MenuAndAuths;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-03-12 16:38
 * @Description:
 */
@RestController
@RequestMapping("/sys/menu")
@Api(tags = "后台菜单接口")
public class MenuController {


    @Autowired
    private SysMenuService sysMenuService;


    /**
     * 加载蔬菜单和权限
     *
     * @return
     */
    @GetMapping("/nav")
    @ApiOperation(value = "加载用户菜单和权限的接口")
    public ResponseEntity<MenuAndAuths> loadMenuAndAuths() {
        //获取当前用户
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        //查询菜单
        List<SysMenu> menus = sysMenuService.loadUserMenu(userId);
        //获取权限
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        //创建一个返回值
        MenuAndAuths menuAndAuths = new MenuAndAuths();
        menuAndAuths.setMenus(menus);

        List<String> auths = new ArrayList<>();
        authorities.forEach(auth -> {
            auths.add(auth.getAuthority());
        });
        menuAndAuths.setAuths(auths);
        return ResponseEntity.ok(menuAndAuths);
    }

}
